<template>
  <div class="orders-container">
    <!-- 搜索区域 -->
    <div class="search-form">
      <div class="search-row">
        <div class="search-item">
          <span class="label">订单号:</span>
          <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable />
        </div>
        <div class="search-item">
          <span class="label">订单状态:</span>
          <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
            <el-option label="全部" value="" />
            <el-option v-for="item in orderStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
        <div class="search-item">
          <span class="label">创建时间:</span>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            :shortcuts="dateShortcuts"
          />
        </div>
        <div class="search-buttons">
          <el-button type="primary" @click="fetchData" :loading="loading">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </div>
      </div>
    </div>
    
    <!-- 网络错误提示 -->
    <el-alert
      v-if="networkError"
      type="error"
      :title="networkErrorMessage"
      description="请检查网络连接，然后点击重试按钮刷新数据"
      show-icon
      :closable="false"
      style="margin-bottom: 20px;"
    >
      <template #default>
        <div class="alert-actions">
          <el-button size="small" type="primary" @click="fetchData">
            重试
          </el-button>
        </div>
      </template>
    </el-alert>

    <!-- 表格区域 -->
    <el-table v-loading="loading" :data="orderList" border stripe>
      <el-table-column type="index" label="序号" width="50" />
      <el-table-column prop="orderNo" label="订单号" width="180" />
      <el-table-column label="用户信息" width="120">
        <template #default="scope">
          {{ scope.row.user?.name || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="totalAmount" label="订单金额" width="120">
        <template #default="scope">
          ¥{{ scope.row.totalAmount || 0 }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="订单状态" width="100">
        <template #default="scope">
          <el-tag :type="getOrderStatusType(scope.row.status)">
            {{ getOrderStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column prop="payTime" label="支付时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleDetail(scope.row)">详情</el-button>
          <el-button v-if="scope.row.status === 1" type="success" link @click="handleShipment(scope.row)">发货</el-button>
          <el-button v-if="scope.row.status === 0" type="danger" link @click="handleCancel(scope.row)">取消</el-button>
        </template>
      </el-table-column>
      <!-- 空数据提示插槽 -->
      <template #empty>
        <div class="empty-text">
          <el-icon><DocumentDelete style="font-size: 30px; color: #909399; margin-bottom: 10px" /></el-icon>
          <p>暂无订单数据</p>
        </div>
      </template>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 发货对话框 -->
    <el-dialog
      v-model="shipDialogVisible"
      title="订单发货"
      width="500px"
    >
      <el-form :model="shipForm" label-width="100px">
        <el-form-item label="快递公司">
          <el-input v-model="shipForm.expressCompany" placeholder="请输入快递公司"></el-input>
        </el-form-item>
        <el-form-item label="快递单号">
          <el-input v-model="shipForm.expressNo" placeholder="请输入快递单号"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shipDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmShip">确认发货</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrderList, updateOrderStatus } from '@/api/order'
import { getOrderStatusType, getOrderStatusText } from '@/utils/format'
import { DocumentDelete } from '@element-plus/icons-vue'

const router = useRouter()
const loading = ref(false)
const orderList = ref([])
const total = ref(0)
const dateRange = ref([])
const currentOrder = ref(null)
const shipDialogVisible = ref(false)
const shipForm = ref({
  expressCompany: '',
  expressNo: ''
})
const networkError = ref(false)
const networkErrorMessage = ref('')

// 订单状态选项
const orderStatusOptions = [
  { value: 0, label: '待付款' },
  { value: 1, label: '待发货' },
  { value: 2, label: '待收货' },
  { value: 3, label: '已完成' },
  { value: 4, label: '已取消' }
]

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  orderNo: '',
  status: '',
  startTime: '',
  endTime: ''
})

// 监听日期范围变化
watch(dateRange, (val) => {
  if (val && val.length === 2) {
    queryParams.startTime = val[0]
    queryParams.endTime = val[1]
  } else {
    queryParams.startTime = ''
    queryParams.endTime = ''
  }
})

// 获取订单列表
const fetchData = async () => {
  loading.value = true
  networkError.value = false // 重置网络错误状态
  
  try {
    const res = await getOrderList(queryParams)
    // 检查API返回的数据格式
    console.log('订单API返回数据:', res)
    
    // 处理不同的返回格式情况
    if (res.data && res.data.list) {
      // 标准列表格式
      orderList.value = res.data.list
      total.value = res.data.total || 0
    } else if (res.data && Array.isArray(res.data)) {
      // 直接返回数组的情况
      orderList.value = res.data
      total.value = res.data.length
    } else if (res.data && res.data.items) {
      // items格式
      orderList.value = res.data.items
      total.value = res.data.total || res.data.items.length
    } else {
      // 其他情况，设置为空数组
      orderList.value = []
      total.value = 0
      console.error('未知的API返回格式:', res)
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
    networkError.value = true
    networkErrorMessage.value = '获取订单列表失败，请稍后重试'
    // 出错时设置为空数组
    orderList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handleCurrentChange = (val) => {
  queryParams.page = val
  fetchData()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  queryParams.page = 1
  fetchData()
}

// 查看订单详情
const handleDetail = (row) => {
  router.push(`/orders/${row.id}`)
}

// 处理发货
const handleShipment = (row) => {
  currentOrder.value = row
  shipForm.value = {
    expressCompany: '',
    expressNo: ''
  }
  shipDialogVisible.value = true
}

// 确认发货
const confirmShip = async () => {
  if (!shipForm.value.expressCompany || !shipForm.value.expressNo) {
    ElMessage.warning('请填写完整的快递信息')
    return
  }

  try {
    await updateOrderStatus(currentOrder.value.id, { 
      status: 2, 
      expressCompany: shipForm.value.expressCompany,
      expressNo: shipForm.value.expressNo 
    })
    ElMessage.success('发货成功')
    shipDialogVisible.value = false
    fetchData() // 刷新订单列表
  } catch (error) {
    ElMessage.error('发货失败')
  }
}

// 取消订单
const handleCancel = (row) => {
  ElMessageBox.confirm('确认取消该订单?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await updateOrderStatus(row.id, { status: 4 })
      ElMessage.success('订单已取消')
      fetchData() // 刷新订单列表
    } catch (error) {
      ElMessage.error('取消订单失败')
    }
  }).catch(() => {})
}

// 重置查询
const resetQuery = () => {
  queryParams.orderNo = ''
  queryParams.status = ''
  queryParams.startTime = ''
  queryParams.endTime = ''
  dateRange.value = []
  queryParams.page = 1
  fetchData()
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.orders-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 18px 20px;
}

.search-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  width: 100%;
}

.search-item {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 10px;
}

.label {
  margin-right: 8px;
  white-space: nowrap;
}

.search-item .el-input,
.search-item .el-select,
.search-item .el-date-picker {
  min-width: 180px;
}

.search-buttons {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.search-buttons .el-button {
  min-width: 80px;
  margin-left: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 响应式布局调整 */
@media (max-width: 1200px) {
  .search-row {
    flex-wrap: wrap;
  }
  
  .search-buttons {
    margin-left: 0;
    margin-top: 10px;
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
}

.alert-actions {
  margin-top: 10px;
}

.empty-text {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  padding: 40px 0;
}

.empty-text p {
  margin-top: 10px;
  font-size: 14px;
}
</style> 